<?php

namespace App\Exports;

use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;

class RestoreOrdersExport extends DefaultValueBinder implements FromArray, WithHeadings, WithCustomValueBinder
{
    use Exportable;

    /**
     * 成功的订单 key
     * @var string
     */
    protected $successfulOrdersRedisHKey = 'RESTORE_ORDERS_BY_CANCELED:%s:SUCCESSFUL_ORDERS';

    /**
     * 失败的订单 key
     * @var string
     */
    protected $failedOrdersRedisHKey = 'RESTORE_ORDERS_BY_CANCELED:%s:FAILED_ORDERS';

    private $batchNumber;

    private $type;

    public function __construct($batchNumber, $type = 'successful')
    {
        $this->batchNumber = $batchNumber;
        $this->type = $type;
    }

    public function headings(): array
    {
        return [
            '原订单号',
            '新订单号'
        ];
    }

    public function array(): array
    {
        $result = [];
        foreach (Redis::hgetall(
            sprintf(
                $this->type === 'successful' ? $this->successfulOrdersRedisHKey : $this->failedOrdersRedisHKey,
                $this->batchNumber)
        ) ?? [] as $originalOrder => $newOrder) {
            $result[] = [
                (string) $originalOrder,
                (string) $newOrder
            ];
        }

        return $result;
    }

    public function bindValue(Cell $cell, $value)
    {
        $cell->setValueExplicit($value, DataType::TYPE_STRING);

        return true;
    }
}
